<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 * @author   howe <howe1995@163.com>
 */

namespace App\Helper;

use Exception;
use Hashids\Hashids;

/**
 * ID加密辅助类.
 */
class HashIdsHelper
{
    /**
     * 长度.
     * @var int
     */
    public static $length = 8;

    /**
     * 为安全起见需要修改为自己的秘钥.
     * @var string
     */
    public static $secretKey = 'copy_wechat_im_api';

    /**
     * @var Hashids
     */
    protected static $hashIds;

    /**
     * 加密.
     *
     * @param mixed ...$numbers
     */
    public static function encode(...$numbers): string
    {
        return self::getHashIds()->encode(...$numbers);
    }

    /**
     * 解密.
     * @return array|int|int[]|mixed
     * @throws Exception
     */
    public static function decode(string $hash)
    {
        $data = self::getHashIds()->decode($hash);
        if (empty($data)) {
            throw new Exception('解密失败');
        }

        return count($data) == 1 ? $data[0] : $data;
    }

    /**
     * 获取 HashIds 实例.
     */
    private static function getHashIds(): Hashids
    {
        if (! self::$hashIds instanceof Hashids) {
            self::$hashIds = new Hashids(self::$secretKey, self::$length);
        }

        return self::$hashIds;
    }
}
